<template>
  <el-dialog :visible.sync="isShow" width="800px" destroy-on-close @close="close" :title="title">
    <el-form v-if="currentDialog == 'createUser' || currentDialog == 'updateUser'" :model="itemModel" :rules="rules" ref="itemModel" label-width="120px" :inline="true">
      <el-form-item label="开放平台" prop="openshop" v-if="userModel.role=='admin'">
        <el-select v-model="itemModel.openshop"  placeholder="请选择" clearable>
          <el-option v-for="item in openshopOptions" :key="item.id" :label="item.shopName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="角色" prop="role">
        <el-select v-model="itemModel.role"  placeholder="请选择" clearable>
          <el-option v-for="item in roleOptions" :key="item.key" :label="item.name" :value="item.key"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="itemModel.nickname" placeholder="请输入昵称" clearable maxlength='20' show-word-limit></el-input>
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <el-input v-model="itemModel.phone" placeholder="请输入手机号码" clearable maxlength='11' show-word-limit></el-input>
      </el-form-item>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="itemModel.username" placeholder="请输入用户名" clearable></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password" v-if="currentDialog == 'createUser'">
        <el-input
          :key="passwordType"
          ref="password"
          v-model="itemModel.password"
          :type="passwordType"
          placeholder="请输入密码"
          name="password"
          tabindex="2"
          autoComplete="new-password"
        />
        <span class="show-pwd" @click="showPwd">
          <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
        </span>
      </el-form-item>
      <el-form-item style="margin-top: 50px">
        <el-button type="primary" @click="submitForm('itemModel')">保存</el-button>
      </el-form-item>
    </el-form>
    <!-- 修改推荐人 -->
    <el-form :model="itemModel" :rules="rules" ref="itemModel" label-width="120px" v-if="currentDialog == 'updataParent'">
      <el-descriptions title="当前用户信息" :column="1" border :labelStyle="{width: '120px'}">
        <el-descriptions-item label="会员ID">{{ itemModel.code }}</el-descriptions-item>
        <el-descriptions-item label="当前推荐人ID">{{ itemModel.parentModel && itemModel.parentModel.code }}</el-descriptions-item>
      </el-descriptions>
      <el-form label-position="top" style="margin-top: 20px">
        <el-form-item label="请输入推荐人手机号或者ID" prop="parentCode">
          <el-row type="flex">
            <el-input v-model="searchValue" placeholder="请输入" clearable></el-input>
            <el-button @click="handleSearch" type="primary" icon="el-icon-search" style="margin-left:40px">搜索</el-button>
          </el-row>
        </el-form-item>
      </el-form>
      <el-descriptions title="修改推荐人为" :column="1" border v-if="itemForm.code">
        <el-descriptions-item label="会员ID" :labelStyle="{width: '120px'}">{{ itemForm.code }}</el-descriptions-item>
        <el-descriptions-item label="会员手机号">{{ itemForm.phone }}</el-descriptions-item>
      </el-descriptions>
      <el-form-item style="margin-top: 50px">
        <el-button type="primary" @click="submitForm('itemModel')">确认修改</el-button>
      </el-form-item>
    </el-form>
    <el-form :model="itemModel" :rules="rules" ref="itemModel" label-width="120px" label-position="left" v-if="currentDialog == 'updateUserForPhone'">
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="itemModel.phone" placeholder="请输入用户手机号" clearable maxlength="11"></el-input>
      </el-form-item>
      <el-form-item style="margin-top: 50px">
        <el-button type="primary" @click="submitForm('itemModel')">保存</el-button>
      </el-form-item>
    </el-form>
    <el-form :model="itemModel" :rules="rules" ref="itemModel" label-width="120px" label-position="left" v-if="currentDialog == 'updateUserForRank' || currentDialog == 'updateUserForRank_high'">
      <el-form-item label="会员ID" prop="rank">
        <div>{{itemModel.code}}</div>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <div>{{itemModel.phone}}</div>
      </el-form-item>
      <el-form-item label="调整级别" prop="rank" v-if="currentDialog == 'updateUserForRank'">
        <el-select v-model="itemModel.rank"  placeholder="请选择" clearable>
          <el-option v-for="item in rankOptions" :key="item.id" :label="item.rankName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="调整俱乐部级别" prop="rank_high" v-if="currentDialog == 'updateUserForRank_high' && userModel.openshopModel.isUse9934">
        <el-select v-model="itemModel.rank_high"  placeholder="请选择" clearable>
          <el-option v-for="item in rankOptions_high" :key="item.id" :label="item.rankName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item style="margin-top: 50px">
        <el-button type="primary" @click="submitForm('itemModel')">保存</el-button>
      </el-form-item>
    </el-form>
    <!-- 升级成为股东 -->
    <el-form :model="itemModel" :rules="rules" ref="itemModel" label-width="120px" label-position="left" v-if="currentDialog == 'updateUserForUpGd'">
      <el-form-item label="会员ID" prop="rank">
        <div>{{itemModel.code}}</div>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <div>{{itemModel.phone}}</div>
      </el-form-item>
      <el-form label-position="top" style="margin-top: 20px">
        <el-form-item label="请输入推荐人手机号或者ID" prop="parentCode">
          <el-row type="flex">
            <el-input v-model="searchValue" placeholder="请输入" clearable></el-input>
            <el-button @click="handleSearch" type="primary" icon="el-icon-search" style="margin-left:40px">搜索</el-button>
          </el-row>
        </el-form-item>
        <el-descriptions title="设置推荐人为" :column="1" border v-if="itemForm.code">
          <el-descriptions-item label="会员ID" :labelStyle="{width: '120px'}">{{ itemForm.code }}</el-descriptions-item>
          <el-descriptions-item label="会员手机号">{{ itemForm.phone }}</el-descriptions-item>
        </el-descriptions>
        <el-form-item label="充值金额" prop="money">
          <el-input v-model="itemModel.money" placeholder="请输入金额" type="number" clearable></el-input>
        </el-form-item>
        <el-form-item style="margin-top: 50px">
          <el-button type="primary" @click="submitForm('itemModel')">保存</el-button>
        </el-form-item>
      </el-form>
    </el-form>
    <el-form :model="itemModel" :rules="rules" ref="itemModel" label-width="120px" v-if="currentDialog == 'updateUserForAddIncomesLocked'">
      <el-form-item label="会员ID" prop="rank">
        <div>{{itemModel.code}}</div>
      </el-form-item>
      <el-form-item label="充值金额" prop="money">
        <el-input v-model="itemModel.money" placeholder="请输入金额" type="number" clearable></el-input>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input type="textarea" placeholder="请输入" v-model="itemModel.remark" maxlength="225"></el-input>
      </el-form-item>
      <el-form-item style="margin-top: 50px">
        <el-button type="primary" @click="submitForm('itemModel')">保存</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { createUser, updateUserByUserId, getUserInfoById, updateUserForAddIncome, updateUserForReduceIncome, updateUserForParent, updateUserForRank, updateUserForRank_high, getUserInfoByCode, updateUserForReduceIncomesLocked, updateUserForAddGolds, updateUserForReduceGolds,
  updateUserForAddBalance, updateUserForReduceBalance, updateUserForUpGd, updateUserForAddIncomesLocked} from "@/api/system/user.js";

import { findRoleList } from "@/api/system/role.js";
import md5 from 'js-md5';
import { Loading } from 'element-ui';
import store from '@/store/index.js'

export default {
  components: {},
  data() {
    const validatePassword = (rule, value, callback) => {
      var pwdRegex = new RegExp('(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z]).{6,20}$')
      if (!pwdRegex.test(value)) {
      // if (!value || value.length < 6) {
        callback(new Error('密码6-20位，且必须包含大小写字母、数字'))
      } else {
        callback()
      }
    }
    return {
        isShow: false,
        title: '',
        userId: '',
        userModel: {},
        itemModel: {
          checkByUserInfo: {},
          updateByUserInfo: {},
          createByUserInfo: {},
          roleModel: {},
          deptModel: {},
          photosList: [],
        },
        searchValue: '',
        itemForm: {},
        genderOptions: [
          {key: 'M', name: "男"},
          {key: 'W', name: "女"},
        ],
        marriageOptions: [
          {key: "单身"},
          {key: "恋爱中"},
          {key: "已婚"},
        ],
        passwordType: 'password',
        currentDialog: '',
        roleOptions: null,
        roleParams: {},
        openshopOptions: [],
        rankOptions: [],
        rankOptions_high: [],
        rules: {
            nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
            username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
            role: [{ required: true, message: '请选择角色', trigger: 'blur' }],
            // gender: [{ required: true, message: '请选择性别', trigger: 'blur' }],
            password: [{ required: true, trigger: 'blur', validator: validatePassword }],
            money: [{ required: true, message: '请输入', trigger: 'blur' }],
            remark: [{ required: true, message: '请输入', trigger: 'blur' }],
        },
        fullscreenLoading: null
    }
  },
  created(){
    this.userModel = store.state.user.userModel
  },
  methods:{
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleSearch(){
      if(!this.searchValue){
        this.$message.error('请输入推荐人手机号或者ID');
        return
      }
      getUserInfoByCode({
        memberCode: this.searchValue,
      }).then(res=>{
        if(res.data.code==10000){
         this.itemForm = res.data.data
        }
      })
    },
    show(e){
      this.getRoleOptions()
      this.isShow = true
      this.currentDialog = e.key
      this.title = e.title
      if(this.currentDialog == 'createUser'){
        this.userId = ''
        this.itemModel = {}
      }else if(this.currentDialog == 'updateUser'){
        this.userId = e.rowId
        this.getUserInfo()
      }else{
        this.userId = e.rowId
        this.getUserInfo()
      }
    },
    close(){
        this.isShow = false
        Object.assign(this.$data, this.$options.data())
    },
    //表单提交
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if(this.currentDialog == 'createUser'){
            this.createUser("创建成功")
          }else if(this.currentDialog == 'updateUser'){
            this.updateUser("更新成功")
          }else if(this.currentDialog == 'updataParent'){
            this.updateUserForParent()
          }else if(this.currentDialog == 'updateUserForPhone'){
            this.updateUserForPhone()
          }else if(this.currentDialog == 'updateUserForRank'){
            this.updateUserForRankFun()
          }else if(this.currentDialog == 'updateUserForRank_high'){
            this.updateUserForRank_high()
          }else if(this.currentDialog == 'updateUserForReduceIncomesLocked'){
            this.updateUserForReduceIncomesLocked()
          }else if(this.currentDialog == 'updateUserForUpGd'){
            this.updateUserForUpGd()
          }else if(this.currentDialog == 'updateUserForAddIncomesLocked'){
            this.updateUserForAddIncomesLocked()
          }
          // if(this.userId){
          //   if(this.currentDialog=='updatePassword')
          //     this.updatePassword("更新成功")
          //   else
          //     this.updateUser("更新成功")
          // }else{
          //   this.createUser("创建成功")
          // }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    refuseForm(formName) {
      var that = this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if(this.userId){
            checkRefuse({userId: this.itemModel.id,refuseCause: this.itemModel.refuseCause}).then(res => {
              this.close()
              this.$emit("confirm")
              this.$message({
                message: '审核已拒绝',
                type: 'success'
              })
            })
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    updateUserForAddIncomesLocked(){
      this.fullscreenLoading = Loading.service({ fullscreen: true, text: '处理中，请稍后！'});
      updateUserForAddIncomesLocked({
        userId: this.userId,
        money: this.itemModel.money,
        remark: this.itemModel.remark,
      }).then(res=>{
        this.fullscreenLoading.close()
        if(res.data.code==10000){
          this.close()
          this.$emit("confirm")
          this.$message({
            message: '充值成功',
            type: 'success'
          })
        }
      })
    },
    updateUserForUpGd(){
      this.$alert('是否确定将'+this.itemModel.code+'的股东推荐人设置为'+this.itemForm.code+'?', {
        confirmButtonText: '确定',
        callback: action => {
          this.fullscreenLoading = Loading.service({ fullscreen: true, text: '设置中，请稍后！'});
          updateUserForUpGd({
            userId: this.userId,
            gdParent: this.itemForm.id,
            money: this.itemModel.money
          }).then(res=>{
            this.fullscreenLoading.close()
            if(res.data.code==10000){
              this.close()
              this.$emit("confirm")
              this.$message({
                message: '设置成功',
                type: 'success'
              })
            }
          })
        }
      });
    },
    // 修改推荐人
    updateUserForParent(){
      if(!this.itemForm.code){
        this.$message({
          message: '请填写推荐人Id或手机号',
          type: 'Info'
        })
        return
      }
      this.$alert('是否确定将'+this.itemModel.code+'的推荐人修改为'+this.itemForm.code+'?', {
        confirmButtonText: '确定',
        callback: action => {
          this.fullscreenLoading = Loading.service({ fullscreen: true, text: '团队迁移中，请稍后！'});
          updateUserForParent({
            userId: this.userId,
            parentId: this.itemForm.id
          }).then(res=>{
            this.fullscreenLoading.close()
            if(res.data.code==10000){
              this.close()
              this.$emit("confirm")
              this.$message({
                message: '修改成功',
                type: 'success'
              })
            }
          })
        }
      });
    },
    updateUserForPhone(){
      updateUserByUserId({
        userId: this.userId,
        phone: this.itemModel.phone
      }).then(res => {
        if(res.data.code == 10000){
          this.close()
          this.$emit("confirm")
          this.$message({
            message: '更新成功',
            type: 'success'
          })
        }
      })
    },
    updateUserForRankFun(){
      updateUserForRank({
        userId: this.userId,
        rank: this.itemModel.rank,
      }).then(res => {
        if(res.data.code == 10000){
          this.close()
          this.$emit("confirm")
          this.$message({
            message: '更新成功',
            type: 'success'
          })
        }
      })
    },
    updateUserForRank_high(){
      updateUserForRank_high({
        userId: this.userId,
        rank_high: this.itemModel.rank_high
      }).then(res => {
        if(res.data.code == 10000){
          this.close()
          this.$emit("confirm")
          this.$message({
            message: '更新成功',
            type: 'success'
          })
        }
      })
    },
    getUserInfo(){
      var that = this
      getUserInfoById({
        obj_id: this.userId
      }).then(res => {
        if(res.data.code == 10000){
          this.itemModel = res.data.data
          if (this.itemModel.gender) {
            this.itemModel.genderLabel = this.itemModel.gender == "M" ? "男": "女"
          } else {
            this.itemModel.genderLabel = ""
          }
        }
      });
    },
    createUser(message){
      var that = this
      var itemModel = JSON.parse(JSON.stringify(this.itemModel))
      if(this.itemModel.password){
        itemModel.password = md5(this.itemModel.password).toUpperCase()
      }
      itemModel.birthday = itemModel.birthday ? itemModel.birthday : '2020-11-11'
      itemModel.applyCause = itemModel.applyCause ? itemModel.applyCause : '无'
      createUser(itemModel).then(res => {
        if(res.data.code == 10000){
          this.close()
          this.$emit("confirm")
          that.$message({
            message: message,
            type: 'success'
          })
        }
      });
    },
    updateUser(message){
      var itemModel = JSON.parse(JSON.stringify(this.itemModel))
      itemModel.userId = this.userId
      itemModel.birthday = itemModel.birthday ? itemModel.birthday : '2020-11-11'
      itemModel.applyCause = itemModel.applyCause ? itemModel.applyCause : '无'
      updateUserByUserId(itemModel).then(res => {
        if(res.data.code == 10000){
          this.close()
          this.$emit("confirm")
          this.$message({
            message: message,
            type: 'success'
          })
        }
      });
    },
    updatePassword(message){
      this.itemModel.userId = this.userId
      this.itemModel.password = md5(this.itemModel.password).toUpperCase()
      updateUserByUserId(this.itemModel).then(res => {
        if(res.data.code == 10000){
          this.close()
          this.$emit("confirm")
          this.$message({
            message: message,
            type: 'success'
          })
        }
      })
    },
    getRoleOptions() {
      this.roleParams.status = 1
      findRoleList(this.roleParams).then(res => {
        this.roleOptions = res.data.data.list
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.list-group {
  line-height: 1.15;
}

.show-pwd {
  position: absolute;
  right: 10px;
  top: 0px;
  font-size: 16px;
  cursor: pointer;
  user-select: none;
}

.el-carousel__item h3 {
    color: #475669;
    font-size: 14px;
    opacity: 0.75;
    line-height: 200px;
    margin: 0;
  }

  .el-carousel__item:nth-child(2n) {
    background-color: #99a9bf;
  }

  .el-carousel__item:nth-child(2n+1) {
    background-color: #d3dce6;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
    background-color: #fbfdff;
    border: 1px #cccccc dotted;
  }
</style>
